﻿$import( "SmitearWebGL.Resources.Buffer" );
$import( "SmitearWebGL.Resources.Shader" );

SmitearWebGL.Resources.VertexElementDescription = Class.extend(
{
	init : function( gl, elementSize, stride, offset, type, location )
	{
		this._registClass( "SmitearWebGL.Resources.VertexElementDescription" );
		
		$THROW( location && location != "", "shader attribute location undefined!" );
		
		stride = stride == undefined ? 0 : stride;
		offset = offset == undefined ? 0 : offset;
		type = type == undefined ? gl.FLOAT : type;
		
		this.itemSize = elementSize;
		this.stride = stride;
		this.offset = offset;
		this.dataType = SmitearWebGL.Resources.Buffer.getGlDataType( gl, type );
		this.shaderAttributeLocation = location;
	}
}
);

SmitearWebGL.Resources.VertexBuffer = SmitearWebGL.Resources.Buffer.extend(
{
	/******** constructor ********/
	
	init : function()
	{
		this._super();
		this._registClass( "SmitearWebGL.Resources.VertexBuffer" );
	}
	,
	createElementDescription : function( elementSize, stride, offset, type, location )
	{
		$THROW( this.isResourceCreated(), "该资源还没有被创建." );
		
		if ( ! location ) return false;
		
		if ( ! this._elementDescriptions ) this._elementDescriptions = [];
		
		var desc = new SmitearWebGL.Resources.VertexElementDescription( this.context.gl, elementSize, stride, offset, type, location )
		this._elementDescriptions.push( desc );
		
		return true;
	}
	,
	active : function( shader )
	{
		$THROW( this.isResourceCreated(), "该资源还没有被创建." );
		
		for ( var i = 0; i < this._elementDescriptions.length; ++ i )
		{
			var desc = this._elementDescriptions[i];
			if ( desc.shaderAttributeLocation )
			{
				var attribslot = shader.attributes[desc.shaderAttributeLocation];
				
				if ( attribslot )
				{
					this.context.gl.enableVertexAttribArray( attribslot.location );
					this.context.gl.vertexAttribPointer( attribslot.location,
											desc.itemSize,
											desc.dataType,
											false,
											desc.stride,
											desc.offset );
				}
			}
		}
		
		return SmitearWebGL.Core.HResult.SUCCESS;
	}
}
);
